
from datetime import datetime
from passlib.hash import bcrypt
from flask import current_app, jsonify
from admin_models.model_basic import Account, Dictionary, DictionaryItem, Menu
from utils.extensions import db
from utils.oss import uploadToOss
from utils.tool import create_access_token, setResponseData



def getAllDictionarys():
    try:
        session = db.session
        dict_items = Dictionary.query.all()

        list1 = [item.getList() for item in dict_items]
        list2 = DictionaryItem.getAll(DictionaryItem,session)

        return setResponseData('10000000', 'success', {
          'dictionary': list1,
          'dictionaryItem': list2
        })

    except Exception as e:
        current_app.logger.error(f"数据库操作时发生错误：{e}")
        return setResponseData('00000000', 'fail', "数据库访问错误")


def getDictPage(page, pageSize):
    page_data, total = Dictionary.getPages(Dictionary, page, pageSize)

    final = {
        'page': int(page),
        'pageSize': int(pageSize),
        'list': page_data,
        'total': total
    }

    return setResponseData('10000000', 'success', final)


def getDictList():
    try:
        dict_items = Dictionary.query.all()

        response_data = [item.getList() for item in dict_items]

        return setResponseData('10000000', 'success', response_data)

    except Exception as e:
        current_app.logger.error(f"数据库操作时发生错误：{e}")
        return setResponseData('00000000', 'fail', "数据库访问错误")


def updateDictById(id, data):
    try:
        session = db.session

        Dictionary.update(Dictionary, id, data, session)

        return setResponseData('10000000', 'success', '')

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"更新字典记录时发生错误：{e}")
        return setResponseData('00000000', 'fail', "更新失败")

    finally:
        # 关闭数据库会话
        db.session.close()


def addNewDict(data):
    try:
        session = db.session

        # 调用add_new_record方法添加新记录
        new_record = Dictionary.add(Dictionary, data, session)

        return setResponseData('10000000', 'success', new_record.id)

    except Exception as e:
        # 发生异常时回滚事务
        db.session.rollback()
        current_app.logger.error(f"添加字典记录时发生错误：{e}")
        return setResponseData('00000000', 'fail', "添加失败")

    finally:
        # 不论成功或失败，最终关闭数据库会话
        db.session.close()


def deleteDictById(id):
    try:
        session = db.session

        # 调用delete_by_id方法删除指定ID的记录
        success = Dictionary.delete(Dictionary, id, session)

        if success:
            return setResponseData('10000000', 'success', '')
        else:
            return setResponseData('00000000', 'fail', "删除失败，未找到指定ID的记录")

    except Exception as e:
        # 发生异常时回滚事务
        db.session.rollback()
        current_app.logger.error(f"删除字典记录时发生错误：{e}")
        return setResponseData('00000000', 'fail', "删除失败")

    finally:
        # 不论成功或失败，最终关闭数据库会话
        db.session.close()


def getDictItemPage(page, pageSize, id):
    page_data, total = DictionaryItem.getPages(
        DictionaryItem, page, pageSize, id, db.session)

    final = {
        'page': int(page),
        'pageSize': int(pageSize),
        'list': page_data,
        'total': total
    }

    return setResponseData('10000000', 'success', final)

# 字典項操作


def getDictItemList(id):
    try:
        session = db.session
        list = DictionaryItem.getList(DictionaryItem, id, session)
        return setResponseData('10000000', 'success', list)

    except Exception as e:
        current_app.logger.error(f"数据库操作时发生错误：{e}")
        return setResponseData('00000000', 'fail', "数据库访问错误")


def updateDictItemById(id, data):
    try:
        session = db.session

        DictionaryItem.update(DictionaryItem, id, data, session)

        return setResponseData('10000000', 'success', '')

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"更新字典记录时发生错误：{e}")
        return setResponseData('00000000', 'fail', "更新失败")

    finally:
        # 关闭数据库会话
        db.session.close()


def addNewDictItem(data):
    try:
        session = db.session

        # 调用add_new_record方法添加新记录
        new_record = DictionaryItem.add(DictionaryItem, data, session)

        return setResponseData('10000000', 'success', new_record.id)

    except Exception as e:
        # 发生异常时回滚事务
        db.session.rollback()
        current_app.logger.error(f"添加字典记录时发生错误：{e}")
        return setResponseData('00000000', 'fail', "添加失败")

    finally:
        # 不论成功或失败，最终关闭数据库会话
        db.session.close()


def deleteDictItemById(id):
    try:
        session = db.session

        # 调用delete_by_id方法删除指定ID的记录
        success = DictionaryItem.delete(DictionaryItem, id, session)

        if success:
            return setResponseData('10000000', 'success', '')
        else:
            return setResponseData('10000000', 'success', "删除失败，未找到指定ID的记录")

    except Exception as e:
        # 发生异常时回滚事务
        db.session.rollback()
        current_app.logger.error("删除字典记录时发生错误：{e}")
        return setResponseData('00000000', 'fail', "删除失败")

    finally:
        # 不论成功或失败，最终关闭数据库会话
        db.session.close()


def getMenuList():
    try:
        nav_items = Menu.query.order_by(Menu.sort).all()

        response_data = [item.getList() for item in nav_items]

        return setResponseData('10000000', 'success', response_data)

    except Exception as e:
        # 记录或处理异常
        current_app.logger.error(f"数据库操作时发生错误：{e}")
        return setResponseData('00000000', 'fail', "数据库访问错误")


def addNewMenu(data):
    try:
        session = db.session

        # 调用add_new_record方法添加新记录
        new_record = Menu.add(Menu, data, session)

        return setResponseData('10000000', 'success', new_record.id)

    except Exception as e:
        # 发生异常时回滚事务
        db.session.rollback()
        current_app.logger.error(f"添加菜单时发生错误：{e}")
        return setResponseData('00000000', 'fail', "添加失败")

    finally:
        # 不论成功或失败，最终关闭数据库会话
        db.session.close()


def updateMenuById(id, data):
    try:
        session = db.session

        Menu.update(Menu, id, data, session)

        return setResponseData('10000000', 'success', '')

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"更新字典时发生错误：{e}")
        return setResponseData('00000000', 'fail', "更新失败")

    finally:
        # 关闭数据库会话
        db.session.close()



def deleteMenuById(id):
    try:
        session = db.session

        # 调用delete_by_id方法删除指定ID的记录
        success = Menu.delete(Menu, id, session)

        if success:
            return setResponseData('10000000', 'success', '')
        else:
            return setResponseData('10000000', 'success', "删除失败，未找到指定ID的记录")

    except Exception as e:
        # 发生异常时回滚事务
        db.session.rollback()
        current_app.logger.error("删除菜單记录时发生错误：{e}")
        return setResponseData('00000000', 'fail', "删除失败")

    finally:
        # 不论成功或失败，最终关闭数据库会话
        db.session.close()


def isPsdTrue(account,password):
    try:
        session = db.session
        item = Account.getAccountById(Account, account, session)
        if bcrypt.verify(password,item['password']):
            token = create_access_token({'account': account, 'password': password})

            return setResponseData('10000000', 'success',{'token': token,'userInfo': item})
        else:
            return setResponseData('00000000', '密碼錯誤！', False)

    except Exception as e:
        # 记录或处理异常
        current_app.logger.error(f"数据库操作时发生错误：{e}")
        return setResponseData('00000000', 'fail', "数据库访问错误")

def uploadFile(file):
    try:
        result = uploadToOss(file)
        print('result',result)
        return setResponseData('10000000', 'success', 'https://mtz-dev.oss-cn-beijing.aliyuncs.com/' + file.filename)
    
    except Exception as e:
        # 记录或处理异常
        current_app.logger.error(f"上传失败：{e}")
        return setResponseData('00000000', 'fail', "上传失败：")
    
